package com.google.code.mergeinformer.service.impl;

import com.google.code.mergeinformer.model.security.User;
import com.google.code.mergeinformer.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

/**
 * @author Dmitriy Golubev
 */
@Service
public class UserServiceImpl implements UserService {

    @PersistenceContext
    private EntityManager em;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            return em.createNamedQuery("User.byUsername", User.class)
                    .setParameter("username", username).getSingleResult();
        } catch (NoResultException ex) {
            throw new UsernameNotFoundException("User with username " + username + " does not exist");
        }
    }

    @Override
    public User findUser(String username) {
        return (User) loadUserByUsername(username);
    }
}
